package il.ac.braude.sona.ocsf.server;
import il.ac.braude.sona.constants.Resources;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Properties;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
 
/**
 * Simple Class to send an email using JavaMail API (javax.mail) and Gmail SMTP server
 * @author Dunith Dhanushka, dunithd@gmail.com
 * @version 1.0
 */
public class EmailSenderAPI {
	
	/**
	 * HOST - The smtp host
	 */
    private static String HOST = "smtp.gmail.com";
	/**
	 * USER - The user account to send mail from
	 */
    private static String USER = "ICM.braude@gmail.com";
	/**
	 * PASSWORD - The user password
	 */
    private static String PASSWORD = "ICM102030";
	/**
	 * PORT - The port of service
	 */
    private static String PORT = "465";
    /**
	 * FROM - The address that message will be send from
	 */
    private static String FROM = "ICM.braude@gmail.com";
    /**
	 * STARTTLS - The option of an extension to plain text communication protocols
	 */
    private static String STARTTLS = "true";
    /**
	 * AUTH - The option of making communication authentic
	 */
    private static String AUTH = "true";
    /**
	 * DEBUG - The option of debuging the sending proccess
	 */
    private static String DEBUG = "false";
    /**
	 * SOCKET_FACTORY - The option of validate the identity of the HTTPS server
	 */
    private static String SOCKET_FACTORY = "javax.net.ssl.SSLSocketFactory";
 
    
    /**
	 * Static method to send an email to user
	 * 
	 * @param to - Email address of receiver 
	 * @param subject - The subject of the email
	 * @param text - The message text
	 * @return Runnable - Runnable proccess to send the email
	 */
    public static synchronized Runnable send(final String to,final String subject,final String text) {

        return (new Runnable ()
        {
        	@Override
			public void run(){
        		try {
        			//Use Properties object to set environment properties
        			final Properties props = new Properties();
        			props.put("mail.smtp.host", HOST);
        			props.put("mail.smtp.port", PORT);
        			props.put("mail.smtp.user", USER);
     
        			props.put("mail.smtp.auth", AUTH);
        			props.put("mail.smtp.starttls.enable", STARTTLS);
        			props.put("mail.smtp.debug", DEBUG);
     
        			props.put("mail.smtp.socketFactory.port", PORT);
        			props.put("mail.smtp.socketFactory.class", SOCKET_FACTORY);
        			props.put("mail.smtp.socketFactory.fallback", "false");
        			//Obtain the default mail session
        			Session session = Session.getDefaultInstance(props, null);
 
        			//Construct the mail message
        			MimeMessage message = new MimeMessage(session);
        			message.setText(text);
        			message.setSubject(subject);
        			message.setFrom(new InternetAddress(FROM));
        			message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
        			message.saveChanges();
 
        			//Use Transport to deliver the message
        			Transport transport = session.getTransport("smtp");
        			transport.connect(HOST, USER, PASSWORD);
        			transport.sendMessage(message, message.getAllRecipients());

        			transport.close();
        		} catch (Exception e) {

        			e.printStackTrace();
        		}
        	}
        });
 
    }

    /**
	 * Static method sends Reminder email message to worker 
	 * @param uid - user id to send to
	 * @param rid - request related to message
	 */
    public static void sendReminderToWorker(String uid,String rid){
    	Connection con=null;
    	try {
    		con  = DatabaseController.getConnection();
    		SQLHelper.use(con, DatabaseController.dbName);
    		ArrayList<HashMap<String, String>> results = SQLHelper.select("users","uid='"+uid+"'",con,"email");
			for (HashMap<String, String> hash : results) {
				new Thread (EmailSenderAPI.send(hash.get("email"), "REMINDER",Resources.Strings.RemainderMessageToWorker+rid+Resources.Strings.EmailSignature)).run();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			if (con!=null)
				try {
					con.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
		}
    	
    }
    
  
    /**
	 * main method to test class
	 */
    public static void main(String[] args){
    	send("avitan.avihay@gmail.com","test","test message");
    	sendReminderToWorker("avihay","80");
    }
 
}